package com.katze.boot.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.katze.boot.common.exception.BusinessException;
import com.katze.boot.plugins.security.annotations.RestControllerMapping;
import com.katze.boot.plugins.security.annotations.RestRequestMapping;
import com.katze.boot.system.domain.Role;
import com.katze.boot.system.service.RoleMenuService;
import com.katze.boot.system.service.RoleService;
import com.katze.common.Message;
import com.katze.common.Pagination;
import com.katze.common.controller.BaseController;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@RestControllerMapping("/role")
public class RoleController extends BaseController {

    @Resource
    private RoleService roleService;
    @Resource
    private RoleMenuService roleMenuService;

    @RestRequestMapping(permits = "role:view", skip = true)
    public Message roleList(Pagination pagination, Role role) {
        return toDataTable(roleService.findRoles(pagination, role));
    }

    @RestRequestMapping("/check")
    public Message exists(String roleName) {
        return Message.ok().data(!roleService.exists(roleName));
    }

    @RestRequestMapping("/menu")
    public Message getRoleMenus(Long... roleId) {
        return Message.ok().data(roleMenuService.getRoleMenusByRoleId(roleId));
    }

    @RestRequestMapping(method = RequestMethod.POST, permits = "role:add", description = "新增角色")
    public Message addRole(@RequestBody Role role) {
        this.roleService.createRole(role);
        return Message.ok("新增角色成功");
    }

    @RestRequestMapping(method = RequestMethod.PUT, permits = "role:update", description = "修改角色")
    public Message updateRole(@RequestBody Role role) {
        this.roleService.updateRole(role);
        return Message.ok("修改角色成功");
    }

    @RestRequestMapping(method = RequestMethod.DELETE, permits = "role:delete", description = "删除角色")
    public Message deleteRoles(Long... roleIds) {
        this.roleService.deleteRoles(roleIds);
        return Message.ok("删除角色成功");
    }

    @RestRequestMapping(value = "/excel", method = RequestMethod.POST, permits = "role:export")
    public void export(Pagination pagination, Role role, HttpServletResponse response) throws BusinessException {
        try {
            Object roles = this.roleService.findRoles(pagination, role);
            if (roles instanceof IPage) {
                super.downXlsx("角色信息表", ((IPage<?>) roles).getRecords(), response);
            } else {
                super.downXlsx("角色信息表", (List<?>) roles, response);
            }
        } catch (Exception e) {
            throw new BusinessException("导出Excel失败", e);
        }
    }
}